package com.tangsm.spring.boot.filter.common.filter;

import com.tangsm.spring.boot.filter.common.utli.HttpUtils;
import com.tangsm.spring.boot.filter.common.wrapper.RequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * WebFilter注解实现Filter过滤器
 * @author tangsm
 **/
@Component
@WebFilter(filterName = "WebAnnotationFilter", urlPatterns = "/*")
public class AnnotationRegisterFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(AnnotationRegisterFilter.class);

    @Override
    public void init(FilterConfig config) throws ServletException {
        log.info("WebFilter注解实现Filter过滤器，过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("WebFilter注解实现Filter过滤器，执行过滤操作");

        // 包装HttpServletRequest，目的是让其输入流可重复读
        RequestWrapper requestWrapper = new RequestWrapper((HttpServletRequest) request);

        log.info("WebFilter注解实现Filter过滤器，请求URI：{}", requestWrapper.getRequestURI());

        // json请求打印body信息
        if (HttpUtils.isJsonContent(request)) {
            log.info("WebFilter注解实现Filter过滤器，请求Body：{}", requestWrapper.getBody());
        }

        chain.doFilter(requestWrapper, response);
    }

    @Override
    public void destroy() {
        log.info("WebFilter注解实现Filter过滤器，过滤器销毁");
    }
}
